package ex3;

import common.IRunnable;
import common.Utils;
import ex2.ITokenizer;
import ex2.JflexTokenizer;
import ex2.Token;
import ex2.grammars.GrammarFactory;
import ex2.grammars.GrammarType;
import ex2.grammars.IGrammar;
import fun.parser.Tree;
import ic.ast.Node;
import ic.ast.decl.Program;

import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: Roi
 * Date: 12/6/13
 */
public abstract class Ex3Runnable implements IRunnable {

    protected String programFilename;
    protected String libraryFilename;

    /**
     * Creates ast according to members
     * @return built program ast
     * @throws Exception
     */
    protected Program getAst() throws Exception {
        Program ast = (Program) getAst(programFilename, GrammarType.GRAMMAR_TYPE_PROGRAM);
        if(libraryFilename != null) {
            Program libAst = (Program) getAst(libraryFilename, GrammarType.GRAMMAR_TYPE_LIBRARY);
            ast.getClasses().add(0, libAst.getClasses().get(0));
        }
        return ast;
    }

    /**
     * Creates ast from given filename (.ic)
     * @param filename ic source filename
     * @param grammarType grammar type to use
     * @return built ast
     * @throws Exception
     */
    private Node getAst(String filename, GrammarType grammarType) throws Exception {
        ITokenizer tokenizer = new JflexTokenizer();
        List<Token> tokens = tokenizer.tokenize(Utils.fileToString(filename));
        IGrammar grammar = GrammarFactory.createGrammar(grammarType);
        Tree parseTree = grammar.constructParseTree(tokens);
        return grammar.constructAst(parseTree);
    }
}
